package com.shujia.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

public class Demo5Combiner {

    static class CombinerMap extends Mapper<LongWritable, Text, Text, LongWritable> {
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            //获取一行数据 返回一个字符串
            String line = value.toString();

            String[] split = line.split(",");

            for (String word : split) {

                //构建输出的key
                Text wordKey = new Text(word);

                //value
                LongWritable intValue = new LongWritable(1);

                //将数据写入reduce    每一次输出，相当于输出一行数据
                context.write(wordKey, intValue);
            }
        }
    }


    static class CombinerReduce extends Reducer<Text, LongWritable, Text, LongWritable> {

        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {

            /**
             * 统计单词数量
             *
             */

            Long sum = 0L;

            for (LongWritable value : values) {
                sum = sum + value.get();
            }

            /**
             * 将数据写入hdfs
             */
            LongWritable value = new LongWritable(sum);
            context.write(key, value);

        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf);

        job.setNumReduceTasks(17);

        job.setJarByClass(Demo5Combiner.class);
        job.setJobName("Demo5Combiner");

        job.setMapperClass(CombinerMap.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        //指定reduce端
        job.setReducerClass(CombinerReduce.class);

        //执行输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        /**
         * 增加map的预聚合   combiner
         *
         * 一般在做求和的时候可以使用
         *
         */

        job.setCombinerClass(CombinerReduce.class);

        //指定输入输出路径
        TextInputFormat.addInputPath(job, new Path("/data/words"));

        TextOutputFormat.setOutputPath(job, new Path("/data/out_combiner1"));

        job.waitForCompletion(true);

    }
}
